<?php


namespace app\module\lockServer;


use app\module\hardwareCloud\HardwareClout;
use app\module\lockAuthServer\LockAuth;

use xhadmin\service\api\LockService;

class Lock
{



    /**
     * @param $lockInfo
     * @return mixed
     * 在线
     */
    static function Online($lockInfo)
    {
        if (in_array(mb_substr($lockInfo["lock_sn"], 0, 2), self::$Yjy)) {

        } else {
            if ($lockInfo['lock_type'] == 7) {
                $result = wmjgwHandle($lockInfo['lock_sn'], 'getlplockstate');
                $lockInfo['online'] = $result['online'];
            } else {
                $result = wmjHandle($lockInfo['lock_sn'], 'lockstate');
                mlog("online".json_encode($result));
                $lockInfo['online'] = $result['online'];
                $lockInfo['rssi'] = $result['rssi'];
                $lockInfo['imei'] = $result['imei'];
                $lockInfo['iccid'] = $result['iccid'];
                $lockInfo['version'] = $result['version'];
                $lockInfo['type'] = $result['type'];
                $lockInfo['lockstatus'] = $result['lockstatus'];
            }
        }

        return $lockInfo;

    }

    /**
     * @param $lockInfo
     * @return mixed
     * 添加卡
     */
    static function CardAdd($lockInfo, $cardsn, $endtime)
    {
        if (mb_substr($lockInfo["lock_sn"], 0, 3) == "W89") {
            $CardAdd = HardwareClout::WifiLock()->CardAdd($lockInfo["lock_sn"], $cardsn, $lockInfo["device_cid"], time(), $endtime);

            if ($CardAdd["err"]) {
                $result['state'] = 0;
                $result['state_code'] = 2003;
                $result['state_msg'] = $CardAdd["err"];
            } else {
                $result['state'] = 1;
                $result['state_code'] = 200;
                $result['state_msg'] = "添加卡成功";
            }


        } else {


            $result = wmjManageHandle($lockInfo['lock_sn'], 'addcard', [
                "sn" => $lockInfo['lock_sn'],
                "cardsn" => $cardsn,
                "endtime" => $endtime,

            ]);
        }
        return $result;

    }


    /**
     * @param $lockInfo
     * @return mixed
     * 删除卡
     */
    static function CardDel($lockInfo, $cardsn)
    {
        if (mb_substr($lockInfo["lock_sn"], 0, 3) == "W89") {
            $CardAdd = HardwareClout::WifiLock()->CardDel($lockInfo["lock_sn"], $cardsn, $lockInfo["device_cid"]);

            if ($CardAdd["err"]) {
                $result['state'] = 0;
                $result['state_code'] = 2003;
                $result['state_msg'] = $CardAdd["err"];
            } else {
                $result['state'] = 1;
                $result['state_code'] = 200;
                $result['state_msg'] = "添加卡成功";
            }


        } else {


            $result = wmjManageHandle($lockInfo['lock_sn'], 'delcard', [
                "sn" => $lockInfo['lock_sn'],
                "cardsn" => $cardsn,


            ]);
        }
        return $result;

    }

    /**
     * @param $lockInfo
     * @return mixed
     * 开门
     */
    static function OpenLock($lockInfo)
    {
        if (mb_substr($lockInfo["lock_sn"], 0, 3) == "W89") {
            $OpenLock = HardwareClout::WifiLock()->OpenLock($lockInfo["lock_sn"], $lockInfo["device_cid"]);

            if ($OpenLock["err"]) {
                $result['state'] = 0;
                $result['state_code'] = 2003;
                $result['state_msg'] = $OpenLock["err"];
            } else {
                $result['state'] = 1;
                $result['state_code'] = 200;
                $result['state_msg'] = "开锁成功";
            }


        } else {

            if ($lockInfo["lock_type"] == 7) {
                $result = wmjgwHandle($lockInfo["lock_sn"], 'ctrlgwl');
            } else {
                $result = wmjHandle($lockInfo["lock_sn"], 'openlock');
            }
        }
        return $result;

    }

    static $Yjy = [
        "W8",
        "W8",
        "W7",
    ];

    static function Add($data)
    {

        if (in_array(mb_substr($data["lock_sn"], 0, 2), self::$Yjy)  ) {
            HardwareClout::App()->Register($data["lock_sn"]);
            if (mb_substr($data["lock_sn"], 0, 3) == "W89") {
                $ActivateRes = HardwareClout::WifiLock()->Activate($data["lock_sn"]);
                if ($ActivateRes["err"]) {
                    return ["err" => $ActivateRes["err"]];

                }
            }
            $data["device_cid"] = $ActivateRes["device_cid"];
            $data["admin_pwd"] = $ActivateRes["admin_pwd"];
            $data["online"] = 1;
        } else {
            $data['lock_sn'] = strtoupper($data['lock_sn']);
            $wmjapiresult = wmjHandle($data['lock_sn'], 'postlock');

            if ($wmjapiresult['state'] == 0) {
                return ["err" => $wmjapiresult['state_msg']];
            }
        }

        $data['mobile_check'] = 1;
        $data['applyauth'] = 0;
        $data['applyauth_check'] = 0;
        $data['status'] = 1;
        $data['location_check'] = 0;
        $data['openbtn'] = 1;
        $data['hitshowminiad'] = 1;
        $data['qrshowminiad'] = 1;
        $data['create_time'] = time();
        $data['successimg'] = '/uploads/admin/202007/5f1c6367d68fd.jpg';
        $lock_id = LockService::add($data);
        $qrcodeurl = "https://" . $_SERVER['HTTP_HOST'] . "/minilock?" . "user_id=" . $data['user_id'] . "&lock_id=" . $lock_id;
        $data['lock_qrcode'] = self::createmarkqrcode($qrcodeurl, $data['lock_name']);

        LockService::update(["lock_id" => $lock_id], $data);
        //添加钥匙
        LockAuth::Add($lock_id, $data['member_id'], $data['user_id']);
        return ["err" => null, "lock_id" => $lock_id];

    }

    static function createmarkqrcode($url, $qrcodename)
    {
        $path = app()->getRootPath() . 'public/qrdata/qrcode/';
        $file = time() . '.png';
        $qrcode_file = $path . $file;

        if (!(is_file($qrcode_file))) {
            require_once app()->getRootPath() . '/vendor/phpqrcode/phpqrcode.php';
            $object = new \QRcode();
            $object->png($url, $qrcode_file, QR_ECLEVEL_L, 10);
        }
        $font = app()->getRootPath() . 'public/qrdata/simhei.ttf';
        if ($qrcodename) { // 有文字再往图片上加文字
            $size = 14;
            $box = @imagettfbbox($size, 0, $font, $qrcodename);
            $fontw = abs($box[4] - $box[0]); // 生成文字的width
            $fonth = abs($box[5] - $box[1]);
            $im = imagecreatefrompng($qrcode_file);
            $info = getimagesize($qrcode_file);
            $imgw = $info[0]; // width
            $imgh = $info[1] + $fonth + 10; // height
            $img = imagecreate($imgw, $imgh);//创建一个长为500高为16的空白图片
            imagecolorallocate($img, 0xff, 0xff, 0xff);//设置图片背景颜色，这里背景颜色为#ffffff，也就是白色
            $black = imagecolorallocate($img, 0x00, 0x00, 0x00);//设置字体颜色，这里为#000000，也就是黑色
            $fontx = 10; // 文字距离图片左侧的距离
            if ($imgw > $fontw) {
                $fontx = ceil(($imgw - $fontw) / 2); // 进一法取整
            }
            imagettftext($img, $size, 0, $fontx, ($info[1] + $fonth), $black, $font, $qrcodename);//将ttf文字写到图片中
            // 以 50% 的透明度合并水印和图像
            imagecopymerge($img, $im, 0, 0, 0, 0, $info[0], $info[1], 100);
            // header('Content-Type: image/png');//发送头信息 浏览器显示
            imagepng($img, $qrcode_file);//输出图片，输出png使用imagepng方法，输出gif使用imagegif方法
        }
        return 'https://' . $_SERVER['HTTP_HOST'] . '/qrdata/qrcode/' . $file;
    }
}
